<?php

namespace App\Http\Controllers\H5;

use App\Events\AgentLogin;
use App\Common\Utils\Helper;
use App\Http\Controllers\Controller;
use App\Models\AgentWebsiteLetter;
use App\Models\WebsiteLetter;
use Illuminate\Support\Carbon;

class WebsiteLetterController extends Controller
{
    public function list()
    {
        event(new AgentLogin($this->user->getKey())); // 收信等等
        $paginate = AgentWebsiteLetter::query()
            ->with(['websiteLetter.attachments'])
            ->where([
                'agent_id' => $this->user['id']
            ])
            ->paginate();

        return $this->response->array(
            Helper::dealWithNotCompatibleSimplePaginate(
                $paginate->setCollection(
                    $paginate->getCollection()->each(function ($item) {
                        $item['created_at_timestamp'] = Carbon::parse($item['created_at'])->timestamp;
                        return $item;
                    })
                )
            )
        );
    }

    public function read($id)
    {
        \DB::transaction(function () use ($id) {
            $agentWebsiteLetter = AgentWebsiteLetter::query()->where(['id' => $id, 'agent_id' => \Auth::id()])->firstOrFail();
            if ($agentWebsiteLetter['status'] === AgentWebsiteLetter::STATUS_UNREAD) {
                $agentWebsiteLetter->update(['status' => AgentWebsiteLetter::STATUS_HAVE_READ]);
                WebsiteLetter::query()->findOrFail($agentWebsiteLetter['website_letter_id'])->increment('number_read');
            }
        });

        return $this->response->noContent();
    }
}
